package com.payease.ezt.activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.payease.ezt.receiver.NetStateReceiver;
import com.payease.ezt.R;
import com.payease.ezt.dialog.WebHistoryDialog;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener, NetStateReceiver.NetworkStateListener {
    private Toolbar toolbar;
    private TextView tvTitle;

    public WebView webEZT;
    private ProgressBar pb;

    private ImageView ivBack;
    private ImageView ivForward;
    private ImageView ivRefresh;
    private ImageView ivBook;
    private ImageView ivHome;

    private String homeUrl;
    private String url;
    private WebHistoryDialog dialog;

    private boolean isStop;
    //    Network listener
    private NetStateReceiver netStateReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        initData();

        initView();

        initWebView();

        netStateReceiver = new NetStateReceiver();
        netStateReceiver.setNetWorkStateListener(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netStateReceiver, intentFilter);
    }

    private void initData() {
        homeUrl = getString(R.string.home_url);
        url = homeUrl;
    }

    private void showHistory(WebBackForwardList Items) {
        int size = Items.getSize();

        List<WebHistoryItem> webHistoryItems = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            if (webHistoryItems.contains(Items.getItemAtIndex(i).getOriginalUrl())) continue;
            webHistoryItems.add(Items.getItemAtIndex(i));
        }
        dialog = new WebHistoryDialog();
        dialog.setWebHistoryItems(webHistoryItems);
        dialog.show(getSupportFragmentManager(), "");
    }

    private void initView() {
        pb = (ProgressBar) findViewById(R.id.pb);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tvTitle = (TextView) findViewById(R.id.toolbar_title);

        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivForward = (ImageView) findViewById(R.id.iv_forward);
        ivRefresh = (ImageView) findViewById(R.id.iv_refresh);
        ivBook = (ImageView) findViewById(R.id.iv_book);
        ivHome = (ImageView) findViewById(R.id.iv_home);

        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        tvTitle.setText(R.string.main_page_title);

        ivBack.setOnClickListener(this);
        ivForward.setOnClickListener(this);
        ivRefresh.setOnClickListener(this);
        ivBook.setOnClickListener(this);
        ivHome.setOnClickListener(this);
    }

    private void initWebView() {
        webEZT = (WebView) findViewById(R.id.wb_ezt);
        WebSettings settings = webEZT.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");

        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);

        webEZT.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pb.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pb.setVisibility(View.GONE);
            }
        });

        webEZT.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    pb.setVisibility(View.GONE);
                } else {
                    pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }
        });

        webEZT.loadUrl(url);

    }

    @Override
    protected void onStop() {
        super.onStop();
        isStop = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isStop = false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webEZT.canGoBack()) {
            webEZT.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_right_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_about:
                Intent intent = new Intent(this, AboutUsActivity.class);
                startActivity(intent);
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id) {
            case R.id.iv_back:
                if (webEZT.canGoBack())
                    webEZT.goBack();
                break;
            case R.id.iv_forward:
                if (webEZT.canGoForward())
                    webEZT.goForward();
                break;
            case R.id.iv_refresh:
                webEZT.reload();
                break;
            case R.id.iv_book:
                showHistory(webEZT.copyBackForwardList());
                break;
            case R.id.iv_home:
                webEZT.clearHistory();
                webEZT.loadUrl(url);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netStateReceiver);
    }

    @Override
    public void onStateChange(NetworkInfo.State state) {
        switch (state) {
            case CONNECTED:
                webEZT.loadUrl(homeUrl);
                break;

            case DISCONNECTED:
                if (!isStop) {
                    enterAboutUs();
                }
                break;
        }
    }

    private void enterAboutUs() {
        Intent intent = new Intent(this, AboutUsActivity.class);
        intent.putExtra("isNotNetworkEnter", true);
        startActivity(intent);
    }
}
